package yzbx.personalwebsite.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import yzbx.personalwebsite.config.ConfigData;
import yzbx.personalwebsite.entity.HotTodayEntity;
import yzbx.personalwebsite.service.GetHotTodayService;
import yzbx.personalwebsite.tool.Httptool;
import yzbx.personalwebsite.tool.RedisTool;

import java.util.ArrayList;
import java.util.List;

import static yzbx.personalwebsite.config.Constants.THEME_BILIBILI;

/**
 * {@code @Author} zxm
 * {@code @Description} 获取B站热点数据服务类
 * {@code @Date} 2024/09/30/15:29
 * {@code @Version} 1.0
 */
@Service
public class GetHotTodayServiceBilibili extends GetHotTodayService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetHotTodayServiceBilibili.class);

    public GetHotTodayServiceBilibili(RedisTool redisTool, Httptool httptool) {
        super(redisTool, httptool);
    }

    @Override
    public List<HotTodayEntity> GetData(String logTheme) {
        List<HotTodayEntity> hotTodayList = new ArrayList<>();
        String url = "https://api.bilibili.com/x/web-interface/ranking/v2";
        LOGGER.warn("B站接口访问不成功");
        try {
            JSONObject jsonObject = httptool.doGet(url);
            JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
            for (int i = 0; i < data.size() && hotTodayList.size() < DATA_NUM_MAX; i++) {
                JSONObject item = data.getJSONObject(i);
                LOGGER.info(item.toJSONString());
                HotTodayEntity hotToday = new HotTodayEntity();
                hotToday.setIndex(hotTodayList.size() + 1 + "");
                hotToday.setTitle(item.get("title").toString());
                hotToday.setUrl(item.get("short_link_v2").toString());
                hotTodayList.add(hotToday);
            }
            LOGGER.info("抓取{}数据成功，{}条", logTheme, hotTodayList.size());
        } catch (Exception e) {
            LOGGER.warn("抓取{}数据失败，失败信息：{}", logTheme, e.getMessage());
        }
        return hotTodayList;
    }

    public static void main(String[] args) {
        GetHotTodayServiceBilibili GetHotTodayServiceBilibili = new GetHotTodayServiceBilibili(new RedisTool(new ConfigData()), new Httptool());
        GetHotTodayServiceBilibili.GetData(THEME_BILIBILI);

    }
}
